import $API from '@/api'
import Tokens from '@/store/modules/common/tokens'
import AuthenticationTokens from '@/types/entity/AuthenticationTokens'
import { ref, watch } from 'vue'
import { RiderBasicInfo, SystemSettings } from '@/types/response/rider'
import Event from '@/store/_event/index'
import GEO, { PositioningModel } from '../common/geo'
import RiderSettings from '@/types/entity/RiderSettings'
class TokensImpl extends Tokens<AuthenticationTokens> {
  public async refreshToken(oldToken: AuthenticationTokens): Promise<AuthenticationTokens> {
    const result = await $API.rider.refreshToken(oldToken.refresh_token)
    if (result.success) {
      return result.data
    } else {
      throw new Error(result.message)
    }
  }
  public extractExpireIn(newToken: AuthenticationTokens): number {
    return newToken.refresh_token_expire_in
  }
  public async login(): Promise<boolean> {
    uni.navigateTo({ url: '/pages/login/index' })
    return false
  }
  public getAccessToken(): string | null {
    return this.getValue()?.access_token ?? null
  }
}

export default class UserStore {
  public tokens = new TokensImpl('AuthenticationTokens')
  public info = ref(new RiderBasicInfo())
  public riderSettings = ref(new RiderSettings())
  public systemSettings = ref(new SystemSettings())
  /**
   * 当骑手工作状态改变时
   */
  public workStatusChangeEvent = new Event<number>()
  /**
   * 打开接单设置事件
   */
  public openOrderTakingSettingsEvent = new Event()
  /**
   * 全局GEO(当为动态模式时10s更新一次geo信息)
   */
  public geo = new GEO(PositioningModel.STATIC, 10 * 1000)

  constructor() {
    // 监听监听systemDispatch设置，根据此来运行不同的geo模式
    watch(
      () => this.riderSettings.value.systemDispatch,
      (newValue) => {
        if (newValue == null) return
        if (newValue === 0) {
          // 不是系统分配
          this.geo.setModel(PositioningModel.STATIC)
        } else {
          // 是系统分配
          this.geo.setModel(PositioningModel.LASTING)
        }
      }
    )
  }
}
